//
//  MapViewController.m
//  YiBaoStore
//
//  Created by 吕清毅 on 2018/11/25.
//  Copyright © 2018年 小河. All rights reserved.
//

#import "MapViewController.h"
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <MAMapKit/MAMapKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
//#import <AMapLocationKit/AMapLocationKit.h>
#import "MapTableViewCell.h"
#import "MapDetailsViewController.h"

@interface MapViewController ()<MAMapViewDelegate,AMapSearchDelegate,UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UIView *headView;
@property (nonatomic, strong)  MAMapView *mapView; //地图
@property (nonatomic, strong) AMapSearchAPI *search; //搜索api
@property (nonatomic, strong) MAAnnotationView *userLocationAnnotationView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *addressArray; //周边地址数组
@property (nonatomic, assign)  float lat;
@property (nonatomic, assign)  float lon;
@end

@implementation MapViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = TotalWhite;
    [self setHeadView];
    [self setTable];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    //如果您需要进入地图就显示定位小蓝点，则需要下面两行代码
    _mapView.showsUserLocation = YES;
    _mapView.userTrackingMode = MAUserTrackingModeFollow;
    [_mapView setZoomLevel:16.5 animated:YES]; //设置缩放级别
}
//定位
- (void)updateLocation:(UIButton *)btn
{
    _mapView.showsUserLocation = YES;
    _mapView.userTrackingMode = MAUserTrackingModeFollow;
//    if(self.mapView.userLocation.updating && self.mapView.userLocation.location) {
//        [self.mapView setCenterCoordinate:self.mapView.userLocation.location.coordinate animated:YES];
//        [btn setSelected:YES];
//    }
}

- (void)setTable
{
    if (self.tableView == nil) {
        self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0,self.mapView.bottom, SCREENWIDTH, SCREENHEIGHT-self.mapView.bottom) style:UITableViewStylePlain];
        self.tableView.backgroundColor = TotalWhite;
        self.tableView.delegate = self;
        self.tableView.dataSource = self;
        self.tableView.estimatedRowHeight = 0;
        self.tableView.estimatedSectionHeaderHeight = 0;
        self.tableView.estimatedSectionFooterHeight = 0;
        [self.tableView registerClass:[MapTableViewCell class] forCellReuseIdentifier:@"MapTableViewCell"];
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        self.tableView.rowHeight = 52;
        self.tableView.tableFooterView = [UIView new];
        [TTKUtil setAutomaticallyAdjustsScrollViewInsetsWidth:self.tableView withView:self];
        //self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(getNewData)];
        [self.view addSubview:self.tableView];
    }
}

-  (void)setHeadView
{
    self.headView = [UIView new];
    self.headView.frame = CGRectMake(0, 0, SCREENWIDTH, 120+TopStatusHeight);
    self.headView.backgroundColor = goldColor;
    [self.view addSubview:self.headView];
    
    UIImageView *leftIV = [UIImageView new];
    leftIV.frame = CGRectMake(15, TopStatusHeight+35, 18, 14);
    leftIV.image = [UIImage imageNamed:@"back"];
    [self.headView addSubview:leftIV];
    
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.frame = CGRectMake(8, TopStatusHeight+28, 32, 28);
    leftBtn.backgroundColor = ClearColor;
    [leftBtn addTarget:self action:@selector(leftBtnBackClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.headView addSubview:leftBtn];
    
    UITextField *searchTF = [UITextField new];
    searchTF.frame = CGRectMake(15, self.headView.height-50, SCREENWIDTH-30, 40);
    searchTF.backgroundColor = TotalWhite;
    searchTF.alpha = 0.5;
    searchTF.layer.cornerRadius = 20;
    searchTF.placeholder = @"         小区/写字楼/街道等";
    [self.headView addSubview:searchTF];
    
    UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(15, searchTF.top, searchTF.width, searchTF.height)];
    [btn addTarget:self action:@selector(textChange) forControlEvents:UIControlEventTouchUpInside];
    [self.headView addSubview:btn];
    
    UIImageView *leftSearch = [UIImageView new];
    leftSearch.frame = CGRectMake(20, 11, 18, 18);
    leftSearch.image = [UIImage imageNamed:@"mapSearch"];
    [searchTF addSubview:leftSearch];
    
    //显示地图
    ///地图需要v4.5.0及以上版本才必须要打开此选项（v4.5.0以下版本，需要手动配置info.plist）
    [AMapServices sharedServices].enableHTTPS = YES;
    ///初始化地图
    _mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, self.headView.bottom, SCREENWIDTH, 0.33*SCREENHEIGHT)];
    _mapView.delegate = self;
    ///把地图添加至view
    [self.view addSubview:_mapView];
    
    //定位点
    UIButton *updateBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    updateBtn.frame = CGRectMake(self.mapView.width-56, self.mapView.height-56, 36, 36);
    [updateBtn setBackgroundImage:[UIImage imageNamed:@"mapLocation"] forState:UIControlStateNormal];
    [updateBtn addTarget:self action:@selector(updateLocation:) forControlEvents:UIControlEventTouchUpInside];
    [self.mapView addSubview:updateBtn];
    
    _mapView.showsCompass= NO; //关闭指南针
    _mapView.showsScale= NO;//关闭比例尺
    
    //定位小蓝点
    MAUserLocationRepresentation *r = [[MAUserLocationRepresentation alloc] init];
    r.showsAccuracyRing = NO;///精度圈是否显示，默认YES
    r.showsHeadingIndicator = NO;///是否显示方向指示，默认yes
    r.image = [UIImage imageNamed:@"mapPosition"];
    [_mapView updateUserLocationRepresentation:r];
    
    //地图搜索api
    self.search = [[AMapSearchAPI alloc] init];
    self.search.delegate = self;
}

//根据中心坐标来搜索周边的POI
- (void)searchPoiByCenterCoordinateWithLat:(CGFloat)lat lon:(CGFloat)lon
{
    //构造AMapPOIAroundSearchRequest对象，设置周边请求参数
    AMapPOIAroundSearchRequest *request = [[AMapPOIAroundSearchRequest alloc]init];
    request.location = [AMapGeoPoint locationWithLatitude:lat longitude:lon];
    //request.location = [AMapGeoPoint locationWithLatitude:self.currentLocation.coordinate.latitude longitude:self.currentLocation.coordinate.longitude];
    /*
     //type
     //POI搜索类型共分为以下20种：汽车服务|汽车销售|
     汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|体育休闲服务|医疗保健服务|
     住宿服务|风景名胜|商务住宅|政府机构及社会团体|科教文化服务|交通设施服务|
     金融保险服务|公司企业|道路附属设施|地名地址信息|公共设施
     //cityCode表示POI搜索区域，可以是城市编码也可以是城市名称，也可以传空字符串，空字符串代表全国在全国范围内进行搜索
     */
    request.radius = 1000;
    request.keywords = @"汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|医疗保健服务|住宿服务|风景名胜|商务住宅|政府机构及社会团体|科教文化服务|交通设施服务|金融保险服务|公司企业";
    //汽车维修";
    request.types = @"风景名胜|公司企业|汽车服务|商务住宅|政府机构";
    request.sortrule = 0; //0 按照距离排序 1 综合排序
    request.requireExtension = YES;
    request.requireSubPOIs = YES;
    [self.search AMapPOIAroundSearch:request]; //周边搜索
}

/*
 poi搜索回调
 */
- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response
{
     [self.addressArray removeAllObjects];
    if (response.pois.count == 0)
    {
        return;
    }
    self.addressArray = [NSMutableArray arrayWithArray:response.pois];
    [self.tableView reloadData];
}


#pragma mark -- mapViwe delegate
- (void)mapView:(MAMapView *)mapView regionDidChangeAnimated:(BOOL)animated {
    
    _lat = mapView.userLocation.location.coordinate.latitude;
    _lon = mapView.userLocation.location.coordinate.longitude;
    NSLog(@"curr1 = %.2f \n curr2=%.2f",_lat,_lon);
    [self searchPoiByCenterCoordinateWithLat:_lat lon:_lon];
}

- (void)mapView:(MAMapView *)mapView mapDidMoveByUser:(BOOL)wasUserAction
{
    NSLog(@"移动结束");
}

//修改默认定位点
- (void) mapView:(MAMapView *)mapView didAddAnnotationViews:(NSArray *)views
{
    
     MAAnnotationView *view = views[0];
    // 放到该方法中用以保证userlocation的annotationView已经添加到地图上了。
    if ([view.annotation isKindOfClass:[MAUserLocation class]])
    {
        MAUserLocationRepresentation *pre = [[MAUserLocationRepresentation alloc] init];
//        pre.fillColor = [UIColor colorWithRed:0.9 green:0.1 blue:0.1 alpha:0.3];
//        pre.strokeColor = [UIColor colorWithRed:0.1 green:0.1 blue:0.9 alpha:1.0];
        pre.image = [UIImage imageNamed:@"mapPosition"];
      //  pre.lineWidth = 3;
        [self.mapView updateUserLocationRepresentation:pre];
        
        view.calloutOffset = CGPointMake(0, 0);
        view.canShowCallout = YES;
        view.highlighted = YES;
        self.userLocationAnnotationView = view;
    }
}

- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id <MAAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MAUserLocation class]]) {
        return nil;
    }
    [mapView selectAnnotation:annotation animated:YES];
    
    return nil;
}

#pragma mark -- tableView delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.addressArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //MapTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MapTableViewCell"];
    MapTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (cell == nil) {
        cell = [[MapTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MapTableViewCell"];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.indexPath = indexPath;
    
    AMapPOI *model = self.addressArray[indexPath.row];
    [cell getModel:model];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    AMapPOI *model = self.addressArray[indexPath.row];
    if (self.callBack) {
        self.callBack(model.name,model.province,model.city,model.district,model.address,model.location.latitude,model.location.longitude);
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)textChange
{
    MapDetailsViewController *details = [MapDetailsViewController new];
    details.callBack = ^(NSString * _Nonnull location, NSString * _Nonnull province, NSString * _Nonnull city, NSString * _Nonnull district, NSString * _Nonnull address, double latitude, double longitude) {
        self.callBack(location,province,city,district,address,latitude,longitude);
        for (UIViewController *controller in self.navigationController.viewControllers)
        {
            NSLog(@"view = %@",self.navigationController.viewControllers);
            if ([self.back isEqualToString:@"myself"]) { //个人中心修改地址
             
                if ([controller isKindOfClass:[EditAddressViewController class]])
                {
                    EditAddressViewController *addVC =(EditAddressViewController *)controller;
                    [self.navigationController popToViewController:addVC animated:YES];
                }
            }
            else
            {
                if ([controller isKindOfClass:[ADDNewShopViewController class]])
                {
                    ADDNewShopViewController *mainVC =(ADDNewShopViewController *)controller;
                    [self.navigationController popToViewController:mainVC animated:YES];
                }
            }
        }
    };
    [self.navigationController pushViewController:details animated:YES];
}

- (void)leftBtnBackClick:(UIButton *)btn
{
    [self.navigationController popViewControllerAnimated:YES];
}

@end
